import math
import random
import re
import string
import time
import traceback
from datetime import datetime
from os import path
from typing import List
from urllib.parse import quote

import jieba
from requests_toolbelt import MultipartEncoder
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select

import requests

from bs4 import BeautifulSoup

from apps.model import BankSideInfo, BorrowerInfo, BankSideExtendInfo, File, DiyaPerson
from apps.seleuinms import CreateDriver
from apps.seleuinms.requests.YzyhRequest import YzyhRequest
from apps.seleuinms.requests.common import get_house_qz
from apps.seleuinms.utils import compare, write_image
from apps.seleuinms.utils.request_utils import parse_response
from apps.logger_config import logger
from apps.utils import curtime


def get_cookie_dict(value):
    return {
        'domain': 'bdcserver',
        'name': 'JSESSIONID',
        'value': value
    }


"""抵押申请填报界面调用"""
diya_js = """
function Post(URL, PARAMTERS) {
    //创建form表单
    var temp_form = document.createElement("form");
    temp_form.action = URL;
    //如需打开新窗口，form的target属性要设置为'_blank'
    temp_form.target = "_blank";
    temp_form.method = "post";
    temp_form.style.display = "none";
    //添加参数
    for (var item in PARAMTERS) {
        var opt = document.createElement("textarea");
        opt.name = PARAMTERS[item].name;
        opt.value = PARAMTERS[item].value;
        temp_form.appendChild(opt);
    }
    document.body.appendChild(temp_form);
    //提交数据
    temp_form.submit();
}
window.Post=Post
function fwhsXxlr(bdcdyh, zl, jzmj) {
    var param = {
        hasYgxx:"true",
        bdcdyh:bdcdyh,
        xmly:'bdcdy',
        zl:zl,
        jzmj:jzmj
    };
    var json = new Array();
    json.push({name:"hasYgxx", value: "true"});
    json.push({name:"bdcdyh", value: bdcdyh});
    json.push({name:"xmly", value: 'bdcdy'});
    json.push({name:"zl", value: zl});
    json.push({name:"jzmj", value: jzmj});
    var url = "http://bdcserver:8066/estateplat-bank/queryApplication/getBdcqzAndYwrForYgYdy";
    var flag = "true";
    //先通过登记的验证，验证不通过flag=false
    if (flag === 'true'){
        Post(url,json);
    }
}
window.fwhsXxlr=fwhsXxlr
"""
exec_js = "fwhsXxlr('{BDCDYH}','{ZL}','{JZMJ}')"

file_base_path = path.abspath(path.join(path.dirname(path.abspath(__file__)), '../../../static/uploads'))

custom_submit_js = """
if ($("#ywlx").val() == "9990414" && "true" == bank_yancheng_clfwq) {
    $("#confirmTablePop").hide();
    var cqzh = $("#bdcqzh_xxlr").val();
    var fczh = $("#fczh_xxlr").val();
    // var tdzh = $("#fdtdzh_xxlr").val();
    if (cqzh == ""&& fczh != "") {
        cqzh = fczh;
    }
    $.ajax({
        url:encodeURI(bankUrl + "/queryApplication/checkSfBaHt?cqzh=" + cqzh),
        type:"GET",
        success:function (data) {
            if (data.msg == "success"){
                if (data.zt == "2"){
                    bootbox.alert("该产权证已存在网签备案合同，不能选择！");
                }else {
                    submitXxlr();
                }
            }else if (data.msg != ""){
                bootbox.alert("验证产权失败："+data.msg);
            }
        }
    })
}else {
    submitXxlr();
}
"""


def random4():
    list_str = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    return datetime.now().strftime('%Y%m%d') + "".join(random.sample(list_str, 4))


def get_file_manager_id_by_no(no: str, cookies: dict):
    """根据预申请编号 查找附件管理id"""
    url = "http://bdcserver:8066/estateplat-bank/action/bank/fjgl?ywxxLsh={no}".format(no=no)
    res = requests.get(url, cookies=cookies)
    res = parse_response(res)

    url = "http://bdcserver:8066/estateplat-bank/action/bank/showDyZyFc?ywidAndDyid={no}&bdcqzh=".format(
        no=res.get('ywidAndQlid'))
    res = requests.get(url)
    content = res.content.decode('utf8')
    list_str = content.split('\n')
    for s in list_str:
        if 'cardReader1.SetURL6("fcm://bdcserver:8066/fileCenter",' in s:
            return s.split('"')[3]
    return ''


def get_ysqbh_by_borrower(extend: BankSideExtendInfo, diyas: List[DiyaPerson], cookies):
    """
    BH: "202001023372"
    CREATETIME: "2020-01-03"
    CREATETIMETEM: "20200103164349"
    DJZT: "受理"
    DM: "1014"
    DYAQR: "中国邮政储蓄银行股份有限公司盐城市分行"
    DYR: "王爱军/邢礼凤"
    ID: "413G4349AHYGN0AU"
    LRZH: "苏(2017)盐城市不动产证明第0031305号"
    ROWNUM_: 1
    SFHCDZZZ: "1"
    SHYJ: "通过"
    SHZT: "1"
    UPDATETIME: "2020-01-03↵        16:48:39"
    YJZT: "未移交"
    YWBM: "1014"
    YWMC: "房屋（构筑物）抵押权注销登记"
    ZL: "市区人民中路56号世纪花园6幢202室"
    ZWLXJSQX: "2037-06-23"
    ZWLXKSQX: "2017-06-23"
    proid: "413G5244HJVFW4BF"
    """
    url = "http://bdcserver:8066/estateplat-bank/queryApplication/queryYwxx"
    params = {
        '_search': 'false',
        'nd': math.ceil(datetime.now().timestamp() * 1000),
        'rows': '10',
        'page': '1',
        'sidx': 'OrderDate',
        'sort': 'asc',
        'bh': None,
        'zjhm': None,
        'dyr': None,
        'zl': extend.house_located,
        'ywlx': None,
        'djzt': None,
        'enable': None
    }
    for d in diyas:
        params['zjhm'] = d.cert_no
        params['dyr'] = d.name
        res = requests.get(url, params=params, cookies=cookies)
        res = parse_response(res)
        if res is None or res.get('total') == 1:
            return res.get('rows')[0]
    params['zl'] = None
    for d in diyas:
        params['zjhm'] = d.cert_no
        params['dyr'] = d.name
        res = requests.get(url, params=params, cookies=cookies)
        res = parse_response(res)
        if res is None or res.get('total') == 1:
            return res.get('rows')[0]
    raise Exception(500, '未在房管局系统中找到已填报的数据')


def upload_files(ysqbh: str, cookies: dict, contract_id):
    no = get_file_manager_id_by_no(ysqbh, cookies)
    files_list_url = "http://bdcserver:8066/fileCenter/node/list.do?token=whosyourdaddy&nid={no}".format(no=no)
    res = requests.get(url=files_list_url)
    res = parse_response(res)
    uploaded_files = [i.get('name') for i in res.get('items')]
    from apps.app import app
    with app.app_context():
        files: List[File] = File.filter_by(history_id=contract_id).all()
    upload_url = "http://bdcserver:8066/fileCenter/file/upload.do"
    file_obj = {}
    for file in files:
        file_obj[file.file_name] = file
    file_keys = [f.file_name for f in files]
    file_keys.sort()

    for file_key in file_keys:
        file = file_obj.get(file_key)
        if file.file_name not in uploaded_files:
            # 上传
            data = {
                'file': (file.file_name, open(path.join(file_base_path, file.id), 'rb'))
            }
            params = {
                'token': 'whosyourdaddy',
                'nid': no,
                'rdnum': random4(),
                'cover': 'true'
            }
            m = MultipartEncoder(data)
            headers = {
                'Content-type': m.content_type
            }
            res = requests.post(upload_url, params=params, data=m, headers=headers)
            parse_response(res)


def get_tudi_no(no, name, cookies):
    url = 'http://bdcserver:8066/estateplat-bank/queryApplication/queryBdcqzXx'
    params = {
        'bdcqzh': no,
        'qlr': name,
        'tdzl': None,
        'xmly': 'gdTdsyq',
        '_search': 'false',
        'nd': math.ceil(datetime.now().timestamp() * 1000),
        'rows': '20',
        'page': '1',
        'sidx': 'OrderDate',
        'sord': 'asc',
    }
    res = requests.post(url, data=params, cookies=cookies)
    return parse_response(res)


USERNAME = 'yzyh001'
PASSWORD = 'zqq811018'


def get_diyawu_info(name, cert_no, zl):
    url = "http://bdcserver:8066/estateplat-bank/queryApplication/queryBdcqzXx"
    params = {
        'bdcqzh': cert_no,
        'qlr': name,
        'zl': zl,
        'cxmd': None,
        'zjhm': None,
        '_search': 'false',
        'nd': math.ceil(datetime.now().timestamp() * 1000),
        'rows': '20',
        'page': '1',
        'sidx': 'OrderDate',
        'sord': 'asc',
    }
    res = requests.get(url, cookies=HouseRequest.cookie_dict, params=params)
    res = parse_response(res)
    if len(res) == 0:
        # 修改权证号
        no = "".join(re.findall('\d+', cert_no))
        if len(no) != 7:
            no = no[-7:]
        params['bdcqzh'] = no
        res = requests.get(url, cookies=HouseRequest.cookie_dict, params=params)
        res = parse_response(res)
        if len(res) == 0:
            # 去除坐落
            params['zl'] = None
            res = requests.get(url, cookies=HouseRequest.cookie_dict, params=params)
            res = parse_response(res)
    return res


# USERNAME = 'newyzyh001'
# PASSWORD = 'jsyc0515'


class HouseRequest(object):
    cookie_dict = {}

    def __init__(self):
        self.driver: WebDriver = None

    def log(self, msg):
        logger.info('不动产系统： 执行信息： %s, time: %s', msg, curtime())

    def login(self):
        res = requests.get('http://bdcserver:8066/estateplat-bank/query/bank/dyaq', allow_redirects=False)
        url = res.headers.get('Location')
        res = requests.get(url)
        cas_cookie = {}
        for cookie_item in res.cookies.items():
            cas_cookie[cookie_item[0]] = cookie_item[1]

        soup = BeautifulSoup(res.content, 'lxml')
        params = {
            'lt': soup.select('input[name="lt"]')[0]['value'],
            '_eventId': 'submit',
            'username': USERNAME,
            'password': PASSWORD,
        }
        headers = {
            'Origin': 'http://bdcserver:8066',
            'Upgrade-Insecure-Requests': '1',
            "Referer": url,
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/87.0.4280.141 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,'
                      'application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'max-age=0',
        }
        res = requests.post(
            url,
            headers=headers,
            data=params,
            cookies=cas_cookie,
            allow_redirects=False
        )
        for cookie_item in res.cookies.items():
            cas_cookie[cookie_item[0]] = cookie_item[1]
        url = res.headers.get('Location')
        requests.get(url)
        HouseRequest.cookie_dict = {
            'JSESSIONID': url.split(';')[1].split('?')[0].split('=')[1]
        }
        return HouseRequest.cookie_dict

    def get_loupan_info(self, name):
        """一手房查询"""
        """根据楼盘名称查询楼盘信息"""
        name_list: List[str] = list(jieba.cut(name))
        for index, item in enumerate(name_list):
            text = name_list[0:len(name_list) - index]
            url = "http://bdcserver:8066/estateplat-bank/queryApplication/getLpbPagesJson?_search=false&nd=1610508279232" \
                  "&rows=7&page=1&sidx=&sord=asc&djsj_search={name}".format(name="".join(text))
            url = quote(url, safe=string.printable)
            res = parse_response(requests.get(url, cookies=HouseRequest.cookie_dict))
            if res.get('itemSize') != 0:
                return self.process_rows(res.get('rows'), name)

    def process_rows(self, rows: List, compare_str):
        if len(rows) == 1:
            return rows[0]
        if len(rows) == 0:
            return None
        max_item = None
        max_compare = 0
        for item in rows:
            zldz = item.get('ZLDZ')
            c = compare(zldz, compare_str)
            if c > max_compare:
                max_compare = c
                max_item = item
        return max_item

    def get_house_info(self, loupan: dict, name: str):
        loupan_id = loupan.get('FW_DCB_INDEX')
        name_list: List[str] = list(jieba.cut(name))
        for index, item in enumerate(name_list):
            text = name_list[0:len(name_list) - index]
            url = "http://bdcserver:8066/estateplat-bank/queryApplication/getLpbXxPagesJson?_search=false&nd" \
                  "=1610523979833&rows=7&page=1&sidx=&sord=asc&lpb_search={name}&id={id}" \
                  "&xmly=bdcdy".format(name="".join(text), id=loupan_id)
            url = quote(url, safe=string.printable)
            res = parse_response(requests.get(url, cookies=HouseRequest.cookie_dict))
            if res.get('itemSize') == 1:
                return res.get('rows')[0]
        return None

    def open_first_house_window(self, house: dict):
        """打开一手房填报界面"""
        # 这里将会打开新的窗口
        if self.driver is None:
            self.driver = CreateDriver.create('chrome')
        if not self.driver.title:
            self.driver.get('http://bdcserver:8066/cas/login')
            self.driver.delete_all_cookies()
            time.sleep(2)
            self.driver.add_cookie({'name': 'JSESSIONID', 'value': self.cookie_dict.get('JSESSIONID')})
            self.driver.get('http://bdcserver:8066/estateplat-bank/query/bank/dyaq')
        current_window = self.driver.current_window_handle

        self.driver.execute_script(diya_js)
        script = exec_js.format(BDCDYH=house.get('BDCDYH'), JZMJ=house.get('JZMJ'), ZL=house.get('ZL'))
        logger.info('open first house for: script: ' + script)
        self.driver.execute_script(script)
        windows = self.driver.window_handles
        new_window = [w for w in windows if w != current_window][0]
        self.driver.switch_to.window(new_window)
        return new_window, current_window

    def open_second_house_window(self, res, no=None, ZSID=None):
        """打开二手房填报界面"""
        # 这里将会打开新的窗口
        if self.driver is None:
            self.driver = CreateDriver.create('chrome')
        if not self.driver.title:
            self.driver.get('http://bdcserver:8066/cas/login')
            self.driver.delete_all_cookies()
            time.sleep(2)
            self.driver.add_cookie({'name': 'JSESSIONID', 'value': self.cookie_dict.get('JSESSIONID')})
            self.driver.get('http://bdcserver:8066/estateplat-bank/query/bank/dyaq')
        # current_window = self.driver.current_window_handle

        # 打开窗口
        """
        BDCDYBH: ""
        BDCDYH: "320903013043GB00025F00210131"
        BDCDYID: "21NH31470CVFW2J9"
        BDCQZH: "苏(2018)盐城市首次登记证第0014175号"
        DWDM: "3209"
        FTJZMJ: 0
        FWJG: "钢筋混凝土结构"
        FWMJ: 13.47
        GYFS: "1"
        GYFSMC: "共同共有"
        JSQX: "2082-06-27"
        MC: ""
        PROID: "21NH3146KBVFW2J6"
        QLRMC: "馨隆花苑21幢全体业主"
        QLRZJH: "913209037732473204"
        SZCS: "-1"
        TDMJ: 0
        XMLY: "bdc"
        YT: "配电房"
        ZCS: "21"
        ZL: "盐城市盐都区创智路55号馨隆花苑21幢配电房"
        ZSID: "21U958144TVFW3WT"
        """
        params = {
            'bdcqzh': res.get('BDCQZH'),
            'zsid': res.get('ZSID'),
            'xmly': res.get('XMLY'),
            'tdzh': None,
            'zl': res.get('ZL'),
            'hasCqxx': None,
            'cqzh': res.get('BDCQZH'),
            'fczh': None,
            'dwdm': res.get('DWDM'),
            'area': 'false',
            'tdzsid': ZSID,
        }
        if no is not None:
            params['tdzh'] = no + ','
        items = []
        for key in params:
            items.append("{0}={1}".format(key, params.get(key)))
        url = "http://bdcserver:8066/estateplat-bank/queryApplication/getBdcqzAndYwr?" + "&".join(items)
        self.driver.get(url)

        # windows = self.driver.window_handles
        # new_window = [w for w in windows if w != current_window][0]
        # self.driver.switch_to.window(new_window)
        # return 'new_window', current_window

    def compile_qlr(self, extend_info: BankSideExtendInfo):
        # 填写所有的元素
        if extend_info.qlr != '中国邮政储蓄银行股份有限公司盐城市分行':
            """当抵押权利人不等于中国邮政储蓄银行股份有限公司盐城市分行 就需要更换"""
            # 更换抵押权利人
            self.driver.find_element_by_id('select2-dyqr_name-container').click()
            wait = WebDriverWait(self.driver, 10)
            wait.until(EC.presence_of_element_located((By.ID, 'select2-dyqr_name-results')))
            results_ul = self.driver.find_element_by_id('select2-dyqr_name-results')
            options = results_ul.find_elements_by_css_selector('.select2-results__option')
            for option in options:
                if option.text == extend_info.qlr:
                    option.click()
                    break
        dyqr_zjh = self.driver.find_element_by_id('dyqr_zjh')
        if dyqr_zjh.get_attribute('value') != extend_info.qlr_cert_no:
            raise Exception(500, '权利人证件号不匹配')
        # 抵押权人电话
        self.driver.find_element_by_id('qlrlxdh').send_keys(extend_info.dyqr_tel)

    def compile_zwr(self, borrowers: List[BorrowerInfo]):
        """借款人"""
        length = len(borrowers)

        dyr_xxlrs = self.driver.find_elements_by_css_selector('#zwr_xxlr')
        # 首先把债务人全删了重新填报
        if len(dyr_xxlrs) > 1:
            for i in dyr_xxlrs:
                self.driver.find_element_by_id('deleteRowzw').click()
            dyr_xxlrs = self.driver.find_elements_by_css_selector('#zwr_xxlr')

        if dyr_xxlrs.__len__() != length:
            for i in list(range(0, length)):
                if i == 0:
                    continue
                # 新增抵押人行
                self.driver.find_element_by_id('addRowzw').click()

            time.sleep(2)

        dyr_xxlrs = self.driver.find_elements_by_css_selector('#zwr_xxlr')
        tel = ''
        for d in borrowers:
            if d.telphone is not None:
                tel = d.telphone
                break

        if len(dyr_xxlrs) != len(borrowers):
            raise Exception(500, '债务人信息与可填写项不匹配')
        for inx, dy in enumerate(borrowers):
            line = dyr_xxlrs[inx]
            item = line.find_element_by_id('zwr_name')
            item.clear()
            item.send_keys(dy.name)
            item = line.find_element_by_id('zwr_zjh')
            item.clear()
            item.send_keys(dy.cert_no)
            telphone = dy.telphone
            if telphone is None or telphone == '':
                telphone = tel
            item = line.find_element_by_id('zwr_dh')
            item.clear()
            item.send_keys(telphone)

    def compile_dyr(self, dys: List[DiyaPerson]):
        length = len(dys)
        dyr_xxlrs = self.driver.find_elements_by_css_selector('#dyr_xxlr')
        # 只有一手房需要新增抵押人信息
        if length != len(dyr_xxlrs):
            for i in list(range(0, length)):
                if i == 0:
                    continue
                # 新增抵押人行
                self.driver.find_element_by_id('addRow').click()
            time.sleep(2)

        dyr_xxlrs = self.driver.find_elements_by_css_selector('#dyr_xxlr')
        tel = ''
        for d in dys:
            if d.telphone is not None:
                tel = d.telphone
                break

        if len(dyr_xxlrs) != len(dys):
            raise Exception(500, '抵押人信息与可填写项不匹配')

        for inx, dy in enumerate(dys):
            line = dyr_xxlrs[inx]
            line.find_element_by_id('dyr_name').send_keys(dy.name)
            line.find_element_by_id('dyr_zjh').send_keys(dy.cert_no)
            telphone = dy.telphone
            if telphone is None or telphone == '':
                telphone = tel
            line.find_element_by_id('dyr_dh').send_keys(telphone)

    def compile_other(self, extend_info, contract_id):
        # 评估价格
        self.driver.find_element_by_id('pgjg_fc').send_keys(extend_info.total_price)
        self.driver.find_element_by_id('bdcjz_fc').send_keys(extend_info.total_price)
        # 权利价格
        self.driver.find_element_by_id('qljz_fc').send_keys(extend_info.contract_amt)

        # 土地
        self.driver.find_element_by_id('pgjg_td').send_keys(0)
        self.driver.find_element_by_id('qljz_td').send_keys(0)

        # 当权利价格填写完成后，担保数额就被填写了。不需要再填写
        # self.driver.find_element_by_id('bdbzqse').send_keys(extend_info.contract_amt)

        # 履行时间
        self.driver.find_element_by_id('zwlxqx_begin').send_keys(extend_info.contract_start_date, Keys.ENTER)
        self.driver.find_element_by_id('zwlxqx_end').send_keys(extend_info.contract_end_date, Keys.ENTER)
        # 隐藏日期输入框
        try:
            self.driver.execute_script("document.querySelector('.WdateDiv').style.display = 'none'")
        except:
            pass

        # 贷款方式
        Select(self.driver.find_element_by_id('dkfs')).select_by_visible_text(extend_info.loan_method)
        # 抵押方式
        Select(self.driver.find_element_by_id('dyfs')).select_by_visible_text(extend_info.dy_method)
        # 抵押顺位
        self.driver.find_element_by_id('dysw').send_keys('1')

        #
        self.driver.find_element_by_id('dbfw').send_keys(extend_info.dbfw)
        self.driver.find_element_by_id('zmfj').send_keys(extend_info.zmdj)
        self.driver.find_element_by_id('dbbz').send_keys(extend_info.dbbz)

        write_image(self.driver, file_name=contract_id)
        # 点击提交
        # 直接执行提交方法

        # self.driver.find_element_by_id('submit').click()
        time.sleep(2)

        write_image(self.driver, file_name=contract_id + '_result')

    def process_first_extend(self, extend: BankSideExtendInfo, info: BankSideInfo):
        borrowers: List[BorrowerInfo] = BorrowerInfo.filter_by(extend_id=extend.id).all()
        if borrowers is None or borrowers.__len__() == 0:
            logger.error('%s 未找到借款人信息', info.custom_name)
            return
        diyas: List[DiyaPerson] = DiyaPerson.filter_by(extend_id=extend.id).all()

        logger.info('%s 搜索的房屋坐落位置为： %s', info.custom_name, extend.house_located)

        files: List[File] = File.filter_by(history_id=extend.id).all()
        if files is None or files.__len__() == 0:
            logger.error('%s 未找到附件', info.custom_name)
            return

        name = extend.house_located
        if not HouseRequest.cookie_dict:
            self.login()
        loupan = self.get_loupan_info(name)
        if loupan is None:
            raise Exception(500, '未找到楼盘信息')
        house = self.get_house_info(loupan, name)
        if house is None:
            raise Exception(500, '未找到房屋信息')
        self.open_first_house_window(house)

        self.compile_qlr(extend)

        self.compile_zwr(borrowers)
        self.compile_dyr(diyas)

        self.compile_other(extend, info.id)

        self.driver.execute_script("checkBdcdyhAndSubmit()")
        time.sleep(3)

        self.process_first_result(extend, diyas)

    def process_first_house(self, contract_id: str):
        """提交一手房预告抵押申请"""
        from apps.app import app
        try:
            with app.app_context():
                info: BankSideInfo = BankSideInfo.get(contract_id)
                if info is None:
                    logger.error('未找到单据')
                    return
                extend_info = BankSideExtendInfo.filter_by(contract_id=contract_id).all()
                if extend_info is None or extend_info.__len__() == 0:
                    logger.error('%s 未找到扩展信息', info.custom_name)
                    return
                for extend in extend_info:
                    self.process_first_extend(extend, info)
        except Exception as e:
            if e.args[0] == '403':
                HouseRequest.cookie_dict.clear()
                self.login()
                self.process_first_house(contract_id)
                return
            if self.driver is not None:
                self.driver.quit()
                self.driver = None
            with app.app_context():
                info = BankSideInfo.get(contract_id)
                custom_name = info.custom_name
                info.state = 'waitUpload'
                info.save(commit=True)
            logger.error('不动产系统填报失败！ 客户信息： %s, error: %s', custom_name, str(e))
            raise
        finally:
            if self.driver is not None:
                self.driver.quit()
                self.driver = None

    def taizhang(self, located, main_borrower):
        url = "http://bdcserver:8066/estateplat-bank/queryApplication/index?enable=true&rid=D8F4B71FFD5749ECB83A7A6B46E11A2A"
        self.driver.get(url)

        wait = WebDriverWait(self.driver, 20, poll_frequency=1)
        wait.until(EC.presence_of_element_located((By.ID, 'zl')))
        self.driver.find_element_by_id('zl').send_keys(located)
        self.driver.find_element_by_id('dyr').send_keys(main_borrower.name)
        self.driver.find_element_by_id('zjhm').send_keys(main_borrower.cert_no)
        # 执行查询

        wait = WebDriverWait(self.driver, 100, poll_frequency=1)
        wait.until(EC.element_to_be_clickable((By.ID, 'search')))
        self.driver.find_element_by_id('search').click()

        # table
        table = self.driver.find_element_by_id('jqGrid')
        wait = WebDriverWait(self.driver, 200, poll_frequency=1)

        def w(_driver):
            rows = table.find_elements_by_tag_name('tr.jqgrow')
            if rows is None:
                return False
            if len(rows) > 1:
                for row in rows:
                    tds = row.find_elements_by_tag_name('td')
                    for td in tds:
                        if '审核中' in td.text:
                            return True
                _driver.find_element_by_id('search').click()
            return len(rows) == 1

        wait.until(w)

        # 为了测试，注释提交过程
        submit: WebElement = self.driver.find_element_by_css_selector('div[title="审核"]')
        if submit is not None and submit.is_enabled():
            submit.click()

        time.sleep(5)

        wait = WebDriverWait(self.driver, 100, poll_frequency=1)
        wait.until(EC.presence_of_element_located((By.ID, 'shyjTablePop')))

        sh = self.driver.find_element_by_css_selector('#shyjTablePop')

        wait = WebDriverWait(self.driver, 100, poll_frequency=1)
        wait.until(EC.presence_of_element_located((By.ID, 'shyj')))
        sh.find_element_by_css_selector('#shyj').send_keys('通过')

        time.sleep(1)

        wait = WebDriverWait(self.driver, 100, poll_frequency=1)
        wait.until(EC.element_to_be_clickable((By.ID, 'save_sh')))

        sh.find_element_by_id('save_sh').click()
        time.sleep(2)

    def process_first_result(self, extend: BankSideExtendInfo, diyas: List[DiyaPerson]):
        try:
            # 上传附件对话框
            fj = self.driver.find_element_by_id('confirmTablePop_fj')
            if fj is not None and fj.is_displayed():
                # 直接调用接口上传附件
                apply_data = get_ysqbh_by_borrower(extend, diyas, HouseRequest.cookie_dict)
                upload_files(apply_data.get('BH'), HouseRequest.cookie_dict, extend.id)

                # 提交单据
                # 跳转到列表界面
                self.driver.get(
                    "http://bdcserver:8066/estateplat-bank/queryApplication/index?rid=7CAFA4510F96457288C5182061F40348"
                )
                wait = WebDriverWait(self.driver, 20, poll_frequency=1)
                wait.until(EC.presence_of_element_located((By.ID, 'zl')))
                self.driver.find_element_by_id('zl').send_keys(extend.house_located)
                self.driver.find_element_by_id('dyr').send_keys(diyas[0].name)
                self.driver.find_element_by_id('zjhm').send_keys(diyas[0].cert_no)
                # 执行查询

                wait = WebDriverWait(self.driver, 100, poll_frequency=1)
                wait.until(EC.element_to_be_clickable((By.ID, 'search')))
                self.driver.find_element_by_id('search').click()

                # table
                table = self.driver.find_element_by_id('jqGrid')
                wait = WebDriverWait(self.driver, 200, poll_frequency=1)

                def w(_driver):
                    rows = table.find_elements_by_tag_name('tr.jqgrow')
                    if rows is None:
                        return False
                    if len(rows) > 1:
                        for row in rows:
                            tds = row.find_elements_by_tag_name('td')
                            for td in tds:
                                if '正在编辑' in td.text:
                                    return True
                        _driver.find_element_by_id('search').click()
                    return len(rows) == 1

                wait.until(w)

                # 为了测试，注释提交过程
                submit: WebElement = self.driver.find_element_by_css_selector('div[title="提交"]')
                if submit is not None and submit.is_enabled():
                    submit.click()
                # self.driver.execute_script("""document.querySelector('div[title="提交"]').style.background = 'red'""")

                wait = WebDriverWait(self.driver, 100, poll_frequency=1)
                wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'button[data-bb-handler="confirm"]')))

                self.driver.find_element_by_css_selector('button[data-bb-handler="confirm"]').click()

                # 跳转到审核台账界面：
                self.taizhang(extend.house_located, diyas[0])

                self.driver.quit()
                self.driver = None
                from apps.app import app
                with app.app_context():
                    # 修改单据状态
                    item = BankSideInfo.get(extend.contract_id)
                    item.state = 'waitApprove'
                    item.save(commit=True)
                return
            # 该不动产单元已存在双预告抵押申请！
            dialogs = self.driver.find_elements_by_css_selector('.bootbox-body')
            if dialogs is not None and len(dialogs) != 0:
                for d in dialogs:
                    if '该不动产单元已存在双预告抵押申请' in d.text:
                        # 已经存在数据直接修改contract状态就好了
                        from apps.app import app
                        with app.app_context():
                            item = BankSideInfo.get(extend.contract_id)
                            item.state = 'waitApprove'
                            item.save(commit=True)
                        return
        except Exception as e:
            logger.error("执行房管局填报过程中错误： %s", traceback.format_exc())
            raise

    def process_second_house(self, contract_id: str):
        try:
            from apps.app import app
            with app.app_context():
                info: BankSideInfo = BankSideInfo.get(contract_id)
                if info is None:
                    logger.error('未找到单据')
                    return
                extend_info: List[BankSideExtendInfo] = BankSideExtendInfo.filter_by(contract_id=contract_id).all()
                if extend_info is None or extend_info.__len__() == 0:
                    logger.error('%s 未找到扩展信息', info.custom_name)
                    return
                for extend in extend_info:
                    if not HouseRequest.cookie_dict:
                        self.login()
                    diyas: List[DiyaPerson] = DiyaPerson.filter_by(extend_id=extend.id).all()
                    borrowers = BorrowerInfo.filter_by(extend_id=extend.id).all()

                    no = None
                    ZSID = None
                    if extend.dkfs == '38':
                        # 当前权证为房屋使用证
                        # 查询土地证
                        if not YzyhRequest.cookie_dict:
                            YzyhRequest.login()
                        res = get_house_qz(extend.collat_id, YzyhRequest.cookie_dict)
                        data = res.get('data')
                        for item in data:
                            # 获取土地证
                            if item.get('ownershipVchrTypeCode') == '39':
                                no = item.get('phyDocNo')
                                no = "".join(re.findall('\d+', no))

                        if no is not None:
                            for d in diyas:
                                res = get_tudi_no(no, name=d.name, cookies=self.cookie_dict)
                                if res is not None and len(res) != 0:
                                    ZSID = res[0].get('ZSID')
                                    break

                        if ZSID is None:
                            pass

                    for dy in diyas:
                        res = get_diyawu_info(dy.name, extend.house_cert_no, extend.house_located)
                        if res is not None and len(res) == 1:
                            # 找到抵押物信息
                            self.open_second_house_window(res[0], no, ZSID)

                            self.compile_qlr(extend)
                            self.compile_zwr(borrowers)
                            self.compile_other(extend, contract_id)

                            # 获取当前不动产系统的坐落位置
                            real_zl = self.driver.find_element_by_id('dywzl').get_attribute('value')

                            extend.house_located = real_zl
                            extend.save()

                            self.driver.execute_script(custom_submit_js)

                            time.sleep(2)

                            self.process_first_result(extend, diyas)
                            break
                        else:
                            raise Exception('500', '未找到 权证号为 %s, 坐落为 %s, 抵押人为 %s 的抵押物信息', extend.house_cert_no,
                                            extend.house_located, [d.name for d in diyas])
        except Exception as e:
            if e.args[0] == '403':
                HouseRequest.cookie_dict.clear()
                self.login()
                self.process_second_house(contract_id)
                return
            logger.error("填报二手房数据报错： 错误信息： %s, 合同编号: %s", traceback.format_exc(), extend.contract_no)
            from apps.app import app
            with app.app_context():
                info: BankSideInfo = BankSideInfo.get(contract_id)
                info.state = 'waitUpload'
                info.save(commit=True)
            raise
        finally:
            if self.driver and self.driver is not None:
                self.driver.quit()
                self.driver = None
